package pt.ipleiria.estg.dei.ei.es2.bio;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.net.NetworkInterface;

import modelo.Contato;


public class MainActivity extends Activity {

    private static final int UPDATEDATA =1 ;
    private boolean hasCheckedIn = false;

    private Contato myContato;

    private SharedPreferences prefs;

    private MenuItem item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //myContato = new Contato("Ricardo","ricardo@gmail.com");

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        item = menu.findItem(R.id.action_checkin);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_checkin) {
            checkin();
        }

        return super.onOptionsItemSelected(item);
    }

    private void checkin() {
        if (!hasCheckedIn) {
            if (hasContactInfo()) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle(getString(R.string.titleConfirmation));
                alertBuilder.setMessage(getString(R.string.pertende_partilhar_info) + myContato);
                alertBuilder.setPositiveButton(getString(R.string.sim), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (hasNetwork()) {
                            hasCheckedIn = true;
                            item.setIcon(R.drawable.ic_action_name2);
                            Intent intent = new Intent(getApplicationContext(), ParticipantListActivity.class);
                            intent.putExtra(ParticipantListActivity.HASCHECKEDIN, hasCheckedIn);
                            startActivity(intent);
                        } else {
                            presentNoNetworkDialog();
                        }
                    }
                });
                alertBuilder.setNegativeButton(getString(R.string.nao), null);
                alertBuilder.show();
            } else {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle(getString(R.string.sem_dados));
                alertBuilder.setMessage(getString(R.string.pretende_preencher_dados_contacto));
                alertBuilder.setPositiveButton(getString(R.string.sim), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                            Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);

                            startActivityForResult(intent, UPDATEDATA);
                        }
                     });
                alertBuilder.setNegativeButton(getString(R.string.nao), null);
                alertBuilder.show();
                item.setIcon(R.drawable.ic_action_name2);
                    //Toast.makeText(this, getString(R.string.no_data), Toast.LENGTH_LONG).show();
                }
                hasCheckedIn = true;
            } else {
            item.setIcon(R.drawable.ic_action_name);
            hasCheckedIn = false;
        }
    }

    private void presentNoNetworkDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(R.string.no_network);
        alertBuilder.setMessage(getString(R.string.no_network_try_later));
        alertBuilder.setNegativeButton(getString(R.string.btnOk),null);
        alertBuilder.show();
    }

    private boolean hasContactInfo()
    {
        String nome = prefs.getString(getString(R.string.name),"");
        String email = prefs.getString(getString(R.string.email),"");

        if(!nome.isEmpty() && !email.isEmpty()){
            myContato = new Contato(nome,email);
            return true;
        }else {
            myContato = null;
            return false;
        }
    }

    private boolean hasNetwork() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        return netInfo !=null && netInfo.isConnectedOrConnecting();

    }

    private void presentConfirmationDialog() {
        if (hasContactInfo()) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setTitle(getString(R.string.titleConfirmation));
            alertBuilder.setMessage(getString(R.string.pertende_partilhar_info) + myContato);
            alertBuilder.setPositiveButton(getString(R.string.sim), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (hasNetwork()) {
                        hasCheckedIn = true;
                        item.setIcon(R.drawable.ic_action_name2);
                        Intent intent = new Intent(getApplicationContext(), ParticipantListActivity.class);
                        intent.putExtra(ParticipantListActivity.HASCHECKEDIN, hasCheckedIn);
                        startActivity(intent);
                    } else {
                        Toast.makeText(getApplicationContext(), getString(R.string.no_network), Toast.LENGTH_LONG).show();
                    }
                }
            });
            alertBuilder.setNegativeButton(getString(R.string.nao), null);
            alertBuilder.show();

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        presentConfirmationDialog();
    }

}

